package main

import (
	"common"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"github.com/gomodule/redigo/redis"
	uuid2 "github.com/google/uuid"
	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
	"logger"
	"net/http"
	"os"
	"time"
)

type AppConfig struct {
	LogPath    string
	ListenPort int
	LoginKey   string
	Redis      common.RedisConfig
}

var appConfig AppConfig
var log = logrus.New()
var redisPoll *redis.Pool

func gameLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	log.Infof("Request=%v", r.Form)
	userName := common.GetRequestValue("username", r)
	passWord := common.GetRequestValue("password", r)

	log.Info("redis ActiveCount=", redisPoll.ActiveCount())
	conn := redisPoll.Get()
	if nil == conn {
		common.LogAndResponse(w, errors.New(""), log, "数据库链接错误")
		return
	}
	defer conn.Close()

	dbAccountName := "accountname:" + userName
	log.Info("dbAccountName= ", dbAccountName)
	value, err := redis.StringMap(conn.Do("HGETALL", dbAccountName))
	if nil != err {
		common.LogAndResponse(w, err, log, "账号查询失败")
		return
	}
	log.Info("账号查询完成 ", value)

	dbPassWorld, ok := value["password"]
	if !ok {
		log.Info("新用户注册 username=", userName)
		_, err := conn.Do("HSET", dbAccountName, "password", passWord)
		if nil != err {
			common.LogAndResponse(w, err, log, "密码保存失败")
			return
		}
	} else {
		if dbPassWorld != passWord {
			common.LogAndResponse(w, errors.New(""), log, "密码错误")
			return
		}
	}

	_, err2 := conn.Do("HSET", dbAccountName, "expiretime", time.Now().Unix()+3)
	if err2 != nil {
		common.LogAndResponse(w, err2, log, "expiretime保存失败")
		return
	}

	sessionId, uidErr := uuid2.NewRandom()
	if nil != uidErr {
		common.LogAndResponse(w, uidErr, log, "sessionId create error")
		return
	}
	_, err3 := conn.Do("HSET", dbAccountName, "sessionid", sessionId)
	if nil != err3 {
		common.LogAndResponse(w, err3, log, "sessionid保存失败")
		return
	}

	token := common.MakeLoginToken(userName, appConfig.LoginKey)
	responseStr := fmt.Sprintf(`{"sessionid":"%s", "errmsg":"", "roleinfo":[%s],"token":"%s","timestamp":"%d"}`, sessionId, "", token, time.Now().Unix())
	log.Infof("response=%s\n", responseStr)
	fmt.Fprintf(w, responseStr)
}

func main() {
	configFilePath := flag.String("path", "./etc/login.config", "config path")
	flag.Parse()
	appConfigData, appConfigDataLength := common.ReadFileData(*configFilePath)
	if nil == appConfigData {
		return
	}

	err := json.Unmarshal(appConfigData[:appConfigDataLength], &appConfig)
	if nil != err {
		fmt.Printf("json file error,path=[%s],err=s:[%s]", *configFilePath, err.Error())
		return
	}
	logger.NewLogger(log, appConfig.LogPath)
	log.Info("login server init start")
	execPath, _ := os.Getwd()
	log.Infof("configFilePath = %s", execPath+*configFilePath)
	redisPoll = common.InitRedisPoll(appConfig.Redis, log)
	if nil == redisPoll {
		return
	}

	mux1 := mux.NewRouter()
	common.RegisterHttpFun(mux1, "/accountinfo/gamelogin", gameLogin, log)
	common.BuildHttpListener(appConfig.ListenPort, mux1, log)
}
